package cn.kgc.itrip.auth.service.impl;

import cn.kgc.itrip.auth.service.IUserService;
import cn.kgc.itrip.auth.service.TokenService;
import cn.kgc.itrip.beans.common.Const;
import cn.kgc.itrip.beans.common.ResponseCode;
import cn.kgc.itrip.beans.common.ServerResponse;
import cn.kgc.itrip.beans.model.pojo.ItripUser;
import cn.kgc.itrip.beans.model.vo.ItripUserVo;
import cn.kgc.itrip.beans.model.vo.tokenVo;
import cn.kgc.itrip.mapper.itripUser.ItripUserMapper;
import cn.kgc.itrip.util.*;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author 阿泽
 */
@Service("iUserService")
@Slf4j
public class IUserServiceimpl implements IUserService {
    /**
     * user登录接口
     */
    @Resource
    private ItripUserMapper itripUserMapper;
    @Resource
    private TokenService tokenService;

    @Resource
    private RedisApi redisApi;

    /**
     * @param userCode  用户名
     * @param password  密码
     * @param userAgent 设备表示
     * @return 是否成功
     */
    @Override
    public ServerResponse usercode(String userCode, String password, String userAgent) {
        if (StringUtils.isBlank(userCode) || StringUtils.isBlank(password)) {
            log.error("在用户登录时发生了参数的错误......");
            return ServerResponse.createByErrorMessage("参数丢失");
        }
        //效验用户名
        Integer value = itripUserMapper.queryUserByUserCode(userCode);
        if (value < 0) {
            log.error("在登录时用户名验证失败");
            return ServerResponse.createByErrorMessage("账户不存在");
        }
        //加密密码
        String Password = MD5Util.MD5EncodeUtf8(password);
        ItripUser user = itripUserMapper.queryUserByUserCodeAndPassword(userCode, Password);
        if (user == null) {
            log.error("在登录时发生了密码错误");
            return ServerResponse.createByErrorMessage("密码不正确");
        }
        log.info(user.getUserName() + "登入成功");
        user.setUserPassword(StringUtils.EMPTY);
        log.info("密码置空完成");
        //TODO 登录成功 等待Token的生成 pc 手机

        String token = tokenService.generateToken(userAgent, user);
        log.info("token生成完成" + token);
        //TODo 保存token
        //判断用户是否为手机
        if (UserAgentUtil.CheckAgent(userAgent)) {
            tokenService.saveToken(token, JSONObject.toJSONString(user), -1);
        } else {
            tokenService.saveToken(token, JSONObject.toJSONString(user), Const.RedisConst.SESSION_TIMEOUT);
        }

        log.info("token保存完成");
        //组装vo
        tokenVo tokenVo = new tokenVo();
        tokenVo.setGenTime(System.currentTimeMillis());
        tokenVo.setExpTime(System.currentTimeMillis() + Const.RedisConst.SESSION_TIMEOUT * 1000);
        tokenVo.setToken(token);
        return ServerResponse.createBySuccess(tokenVo);
    }

    @Override
    public ServerResponse addUser(ItripUserVo itripUserVo, Integer regId) {
        if (regId > 0) {
            if (!checkUserCode(itripUserVo.getUserCode()).isSuccess()) {
                return checkUserCode(itripUserVo.getUserCode());
            }
            ItripUser itripUser = new ItripUser();
            BeanUtils.copyProperties(itripUserVo, itripUser);
            //需要些常量
            itripUser.setUserType(0);
            itripUser.setFlatID(0L);
            itripUser.setUserPassword(MD5Util.MD5EncodeUtf8(itripUserVo.getUserPassword()));

            try {
                Integer rowCount = itripUserMapper.insertItripUser(itripUser);
                if (rowCount > 0) {
                    Integer num = (int) ((Math.random() * 9 + 1) * 100000);
                    String[] str = {num.toString(), "5"};
                    switch (regId) {
                        case 1:
                            //发送Email
                            //MailUtil.activeUser(itripUserVo.getUserCode(),str[0]);
                            MailUtil.sendMail(itripUserVo.getUserCode(), "验证码:", str[0]);
                            log.info("Email发送成功");
                            redisApi.setEx(itripUserVo.getUserCode(), str[0], 5 * 60);
                            break;
                        case 2:
                            //发送手机号
                            SMSSendUtil smsSendUtil = new SMSSendUtil();
                            System.out.println("手机号" + itripUserVo.getUserCode());
                            smsSendUtil.sendSms(itripUserVo.getUserCode(), "1", str);
                            log.info("短信发送成功");
                            redisApi.setEx(itripUserVo.getUserCode(), str[0], 5 * 60);
                            break;
                        default:
                            break;
                    }
                    return ServerResponse.createBySuccess("注册成功");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 激活账户
     *
     * @param user 账户
     * @param code 验证码
     * @return
     */

    @Override
    public ServerResponse activation(String user, String code) {
        log.info("激活账户");
        if (StringUtils.isBlank(user) || StringUtils.isBlank(code)) {
            return ServerResponse.createByErrorMessage("参数丢失");
        }
        if (redisApi.exists(user)) {
            //redis存在
            String value = redisApi.get(user);
            if (value.equals(code)) {
                log.info("修改用户状态");
                Integer rowCount = itripUserMapper.updateUseractivated(user, 1);
                if (rowCount > 0) {
                    log.info("修改用户完毕");
                    redisApi.del(user);
                    log.info("删除redis中的验证码成功");
                    return ServerResponse.createBySuccess("激活成功");
                }
                return ServerResponse.createByErrorMessage("激活失败");
            } else {
                return ServerResponse.createByErrorMessage("验证码错误");
            }
        }
        return ServerResponse.createByErrorMessage("验证码失效或账号不正确");
    }

    @Override
    public ServerResponse checkUserCode(String name) {
        log.info("检查用户名是否存在");
        if (StringUtils.isBlank(name)) {
            log.info("在检查用户名时，发生了参数丢失！！！！！！");
            return ServerResponse.createByErrorMessage(ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        ItripUser user = itripUserMapper.selectUser(name);
        if (user == null) {
            //用户名不存在 可以注册
            return ServerResponse.createBySuccess();
        }
        if (user.getActivated() == 1) {
            //用户名已经激活
            return ServerResponse.createByErrorMessage("用户名已存在并且已经激活");
        } else {
            //当前账户用户名已经被使用没有激活
            //TODO 需要存入redis中的键
            if (redisApi.exists(name)) {
                //验证码已经存在
                return ServerResponse.createByErrorMessage("已有验证码请激活账户");
            } else {
                //验证时间已过
                //TODO 删除数据库中的相关内容，并且返回成功
                itripUserMapper.deleteItripUserByuserCode(name);
                return ServerResponse.createBySuccess();
            }

        }
    }

}